package com.app.qbake.module.mine;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.app.qbake.H5Activity;
import com.app.qbake.R;
import com.app.qbake.module.mine.adapter.VipPkgAdapter;
import com.app.qbake.module.mine.di.VipPkgComponent;
import com.app.qbake.module.mine.event.H5PaySuccessEvent;
import com.app.qbake.module.mine.layout.PkgBuyLayout;
import com.app.qbake.module.mine.mvp.VipPkgView;
import com.app.qbake.module.mine.presenter.VipPkgPresenter;
import com.wind.base.H5Param;
import com.wind.base.bean.Config;
import com.wind.base.bean.User;
import com.wind.base.mvp.view.BaseLoadingFragment;
import com.wind.base.repo.ConfigRepo;
import com.wind.base.repo.UserRepo;
import com.wind.base.request.BaseRequest;
import com.wind.base.utils.ViewInflater;
import com.wind.coder.annotations.Api;
import com.wind.coder.annotations.Heros;
import com.wind.coder.annotations.Param;
import com.wind.data.mine.VipPkgRequest;
import com.wind.data.mine.VipPkgResponse;
import com.wind.data.mine.bean.Pkg;
import com.wind.pingpp.util.PaymentUtil;
import com.wind.toastlib.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

@Heros(
        param = @Param(
                viewCanonicalName = "com.app.qbake.module.mine.mvp.VipPkgView",
                responseCanonicalName = "com.wind.data.mine.VipPkgResponse",
                requestCanonicalName = "com.wind.data.mine.VipPkgRequest"

        ),
        api = @Api(httpMethod = Api.HttpMethod.GET, url = "user/getCombo")
)
public class VipPkgFragment extends BaseLoadingFragment<VipPkgView, VipPkgPresenter, VipPkgComponent, VipPkgResponse>
        implements VipPkgView {

    @Inject
    VipPkgPresenter presenter;
    @BindView(R.id.rv)
    RecyclerView rv;
    VipPkgAdapter mAdapter;

    @BindView(R.id.iv_avatar)
    ImageView iv_avatar;

    @BindView(R.id.tv_name)
    TextView tv_name;

    @BindView(R.id.tv_vip_status)
    TextView tv_vip_status;


    PkgBuyLayout mPkgBuyLayout;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }

            @Override
            public boolean canScrollHorizontally() {
                return false;
            }
        };
        rv.setLayoutManager(manager);
        mAdapter = new VipPkgAdapter(getActivity(), R.layout.item_vip_member);
        rv.setAdapter(mAdapter);

        mPkgBuyLayout = new PkgBuyLayout(getActivity(), new PkgBuyLayout.OnChargeListener() {
            @Override
            public void onChargeLoad(String charge) {
                String payMode=ConfigRepo.getInstance().get(getActivity()).getPing();
                if (!payMode.equals(Config.PAYMODE_PING_YES)){
                    H5Param param=H5Param.obtain(charge,"","");
                    H5Activity.start(getActivity(),param);
                }else {
                    PaymentUtil.startPay(VipPkgFragment.this, charge);
                }
            }
        });
    }

    @Override
    public VipPkgPresenter createPresenter() {
        return presenter;
    }

    @Override
    protected BaseRequest buildLoadingRequest() {
        VipPkgRequest request = new VipPkgRequest();
        request.setType(VipPkgRequest.TYPE_VIP);
        return request;
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_vip_pkg;
    }

    @Override
    public void showPage(VipPkgResponse reponse) {
        List<Pkg> pkgs=reponse.getVipPkgHolder().getPkgList();
        pkgs.get(0).setSelected(true);
        mAdapter.replace(pkgs);
        User loginUser = reponse.getVipPkgHolder().getInfo();
        ViewInflater.inflateImage(iv_avatar, loginUser.getAvatar());
        ViewInflater.inflateText(tv_name, loginUser.getUserName());

        boolean is_vip = loginUser.getIs_vip() == 1;
        if (is_vip) {
            User existUser=UserRepo.getInstance().get(getActivity());
            existUser.setIs_vip(1);
            UserRepo.getInstance().store(getActivity(),existUser);
            tv_vip_status.setText("已开通");

        } else {
            tv_vip_status.setText("未开通");
        }
        mLayoutManager.showContent();
    }


    @OnClick({R.id.tv_open_vip})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.tv_open_vip:
                Pkg pkg = mAdapter.getSelectedItem();
                mPkgBuyLayout.buyPkg(pkg.getId());
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        PaymentUtil.onActivityResult(requestCode, resultCode, data, new PaymentUtil.PaymentCallback() {
            @Override
            public void onPayReturn(PaymentUtil.PaymentState state, String msg) {
                switch (state) {
                    case SUCCESS:
                        //ToastUtil.showToast(getActivity(),msg);
                        //查询一下
                        showOpLoadingIndicator();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                hideOpLoadingIndicator();
                                handlePingppSuccess();
                            }
                        }, 1500);


                        break;
                    case CANCEL:
                    case FAIL:
                    case INVALID:
                    case UNKNOWN:
                        hideOpLoadingIndicator();
                        ToastUtil.showToast(getActivity(), msg);
                        break;
                }
            }

        });
    }

    private void handlePingppSuccess() {
        load();

        //EventBus.getDefault().post(new BuyGoodsSuccessEvent());

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 支付宝网页支付成功回调
     *
     * @param event
     */
    @Subscribe
    public void onH5PaySuccessEvent(H5PaySuccessEvent event) {
        load();
    }
}
